package com.example.config;

import com.example.config.CustomAuthenticationSuccessHandler;
import com.example.config.MyUserDetailsservice;
import com.example.entity.vo.RoleRight;
import com.example.service.impl.SysUserServiceImpl;
import com.example.ulit.JwtUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import java.util.List;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Resource
    private SysUserServiceImpl sysUserService;

    @Resource
    private MyUserDetailsservice myUserDetailsservice;

    @Resource
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    @Resource
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    @Resource
    private CustoAuthenticationFailHandler custoAuthenticationFailHandler;

    @Resource
    CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Resource
    private JWTFilter jwtFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain (HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors().and()
            .formLogin(form -> form
                    .usernameParameter("userName")
                    .passwordParameter("password")
                    .successHandler(customAuthenticationSuccessHandler)
                    .failureHandler(custoAuthenticationFailHandler)
                    .permitAll())
            .authorizeRequests(authorize -> {
                // 允许所有用户访问登录页面
                List<RoleRight> roleRights = sysUserService.selectByUsrRoleIdRoleRight();
                for (RoleRight roleRight : roleRights) {
                    authorize.mvcMatchers(roleRight.getRightUrl()).hasAnyRole(roleRight.getRoleName());
                }
                authorize.antMatchers("login","/uni-app/sys-user/isToken","/uni-app/sys-user/insert","/uni-app/sys-user/sendMessage").permitAll();
                authorize.anyRequest().authenticated(); // 确保这行在最后
            })
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
                .userDetailsService(myUserDetailsservice)
                .exceptionHandling(exception->
                                exception.authenticationEntryPoint(customAuthenticationEntryPoint)
                        .accessDeniedHandler(customAccessDeniedHandler)
                )
        ;
        return http.build();
    }
}